import { createWebHistory, createRouter } from "vue-router"
import MainPage from "./pages/MainPage.vue"
import VideoPage from "./pages/Video.vue";
import FeedbackPage from "./pages/Feedback.vue";
import ManualPage from "./pages/Manual.vue";
import SurveyPage from "./pages/Survey.vue";
const routes = [
  { path: '/', name: "home", component: MainPage, meta: { addQuery: true } },
  { path: '/video', name: "video", component: VideoPage, meta: { addQuery: true } },
  { path: '/feedback', name: "feedback", component: FeedbackPage, meta: { addQuery: true } },
  { path: '/manual', name: "manual", component: ManualPage, meta: { addQuery: true } },
  { path: '/survey', name: "survey", component: SurveyPage, meta: { addQuery: true } },
]
// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const Router = createRouter({
  routes, // short for `routes: routes`
  history: createWebHistory()
});

// Solution here
Router.beforeEach((to, from, next) => {
  if(to.redirectedFrom && to.name==to.redirectedFrom.name){
    next();
    return ;
  }
  // return next();
  if (to.matched.some((record) => (record.meta.addQuery))) {
    let updatedNext = null;
    if (Object.prototype.hasOwnProperty.call(from.query, 'cid')) {
      updatedNext = {
        ...to,
        query: {
          // This line is used to retain other query if there is any
          ...from.query,
          ver: 1,
        },
      };
    }

    if (updatedNext) {
      next(updatedNext)
      return;
    }
  }
  next();

});

export default Router